package com.sanxiau.dormitory.yang.entity;

import com.sanxiau.dormitory.yang.mapper.LeaveMapper;
import com.sanxiau.dormitory.yang.mapper.LoginMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    LoginMapper loginMapper;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        LoginIn currentloginIn = (LoginIn) subject.getPrincipal();
        //System.out.println("currentloginIn-----------"+currentloginIn);
       // System.out.println("currentloginIn.getRemark()-------------"+currentloginIn.getRemark());
        //System.out.println("currentloginIn.getRemark()---------"+currentloginIn.getRemark());
        //System.out.println("currentloginIn-----------"+currentloginIn);
        info.addStringPermission(currentloginIn.getRemark());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证");
        UsernamePasswordToken loginToken = (UsernamePasswordToken) token;
        //System.out.println("loginToken.getPassword():"+String.valueOf(loginToken.getPassword()));
        if ("tel".equals(String.valueOf(loginToken.getPassword()))){
            LoginIn loginIn = loginMapper.queryUserByTel(loginToken.getUsername());
            if (null == loginIn) {
                return null;
            }
            loginIn.setLogin_time(new Date());
            loginIn.setLogin_state("1");
            int num = loginMapper.updateUser(loginIn);
            System.out.println("登陆成功");
            return new SimpleAuthenticationInfo(loginIn,"tel","");
        }else {
            LoginIn loginIn = loginMapper.queryUserByName(loginToken.getUsername());
            if (null == loginIn) {
                return null;
            }
            loginIn.setLogin_time(new Date());
            loginIn.setLogin_state("1");
            int num = loginMapper.updateUser(loginIn);
            System.out.println("登陆成功");

            return new SimpleAuthenticationInfo(loginIn,loginToken.getPassword(),"");
        }
        //System.out.println("loginIn:---------"+loginIn);

    }
}
